package homework.shiwu;

public class TransactionSimulationSimple {
    public static void main(String[] args) {
        Account account1 = new Account("A001", 1000.0);
        Account account2 = new Account("A002", 500.0);

        // 创建事务上下文
        TransactionContext txContext = new TransactionContext();
        txContext.saveState(account1);
        txContext.saveState(account2);

        try {
            // 执行转账
            transfer(account1, account2, 300.0);

            // 模拟失败
            if (0 < 0.5) {
                throw new RuntimeException("模拟系统故障");
            }

            // 提交事务
            txContext.commit();
            System.out.println("转账成功");
        } catch (Exception e) {
            // 回滚事务
            txContext.rollback();
            System.out.println("转账失败，已回滚: " + e.getMessage());
        }

        System.out.println("最终状态:");
        System.out.println(account1);
        System.out.println(account2);
    }

    public static void transfer(Account from, Account to, double amount) {
        from.withdraw(amount);
        to.deposit(amount);
    }
}
